/**
 * 文件上传进度示例
 * 演示如何使用HttpClient的文件上传进度功能
 */

import { HttpClient } from '../src/index.js';

// 创建HttpClient实例
const client = new HttpClient({
  baseURL: 'http://localhost:3000',
  timeout: 30000,
});

// 添加一些中间件 - upload方法现在完全支持中间件机制！
client.use(logger());
client.use(retry({ retries: 3 }));
client.use(auth({ token: 'your-token' }));

// 示例1：使用FormData上传文件并监听进度
async function uploadFileWithProgress() {
  const formData = new FormData();
  
  // 创建一个模拟文件
  const fileContent = new Array(1024 * 1024).fill('a').join(''); // 1MB的文本
  const file = new File([fileContent], 'test.txt', { type: 'text/plain' });
  
  formData.append('file', file);
  formData.append('description', '测试文件上传');

  try {
    const response = await client.post('/post', formData, {
      headers: {
        // 不要手动设置Content-Type，让浏览器自动设置multipart/form-data的boundary
      },
      onUploadProgress: (progressEvent) => {
        const percentCompleted = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        );
        console.log(`上传进度: ${percentCompleted}%`);
        console.log(`已上传: ${progressEvent.loaded} bytes`);
        console.log(`总大小: ${progressEvent.total} bytes`);
      },
      onDownloadProgress: (progressEvent) => {
        if (progressEvent.lengthComputable) {
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          console.log(`下载进度: ${percentCompleted}%`);
        } else {
          console.log(`已下载: ${progressEvent.loaded} bytes`);
        }
      }
    });

    console.log('上传成功:', response.data);
  } catch (error) {
    console.error('上传失败:', error);
  }
}

// 示例2：上传JSON数据并监听进度
async function uploadJsonWithProgress() {
  const jsonData = {
    name: '测试数据',
    data: new Array(1000).fill(0).map((_, i) => ({ id: i, value: `item-${i}` }))
  };

  try {
    const response = await client.post('/post', jsonData, {
      onUploadProgress: (progressEvent) => {
        const percentCompleted = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        );
        console.log(`JSON上传进度: ${percentCompleted}%`);
      }
    });

    console.log('JSON上传成功:', response.data);
  } catch (error) {
    console.error('JSON上传失败:', error);
  }
}

// 示例3：下载文件并监听进度
async function downloadFileWithProgress() {
  try {
    const response = await client.get('/bytes/1048576', { // 下载1MB数据
      responseType: 'blob',
      onDownloadProgress: (progressEvent) => {
        if (progressEvent.lengthComputable) {
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          console.log(`下载进度: ${percentCompleted}%`);
        } else {
          console.log(`已下载: ${progressEvent.loaded} bytes`);
        }
      }
    });

    console.log('下载完成，文件大小:', response.data.size);
  } catch (error) {
    console.error('下载失败:', error);
  }
}

// 运行示例
console.log('=== 文件上传进度示例 ===');
await uploadFileWithProgress();

console.log('\n=== JSON上传进度示例 ===');
await uploadJsonWithProgress();

console.log('\n=== 文件下载进度示例 ===');
await downloadFileWithProgress();